package com.d3works.apps.account.service.app;

import com.d3works.apps.account.db.AccountConfig;
import com.d3works.apps.account.db.repo.AccountConfigRepository;
import com.d3works.apps.base.db.AppAccount;
import com.d3works.apps.base.db.AppBudget;
import com.d3works.apps.base.db.AppInvoice;
import com.d3works.apps.base.db.Company;
import com.d3works.apps.base.db.repo.AppAccountRepository;
import com.d3works.apps.base.db.repo.AppBudgetRepository;
import com.d3works.apps.base.db.repo.AppInvoiceRepository;
import com.d3works.apps.base.db.repo.CompanyRepository;
import com.d3works.apps.base.service.app.AppBaseServiceImpl;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import java.util.List;

@Singleton
public class AppAccountServiceImpl extends AppBaseServiceImpl implements AppAccountService {

  @Inject private AppAccountRepository appAccountRepo;

  @Inject private AppBudgetRepository appBudgetRepo;

  @Inject private AppInvoiceRepository appInvoiceRepo;

  @Inject private AccountConfigRepository accountConfigRepo;

  @Inject private CompanyRepository companyRepo;

  @Override
  public AppAccount getAppAccount() {
    return appAccountRepo.all().fetchOne();
  }

  @Override
  public AppBudget getAppBudget() {
    return appBudgetRepo.all().fetchOne();
  }

  @Override
  public AppInvoice getAppInvoice() {
    return appInvoiceRepo.all().fetchOne();
  }

  @Transactional
  @Override
  public void generateAccountConfigurations() {

    List<Company> companies = companyRepo.all().filter("self.accountConfig is null").fetch();

    for (Company company : companies) {
      AccountConfig config = new AccountConfig();
      config.setCompany(company);
      accountConfigRepo.save(config);
    }
  }
}
